const express = require("express")

const app = express() //创建网站服务器
var server = require('http').createServer(app);
var io = require('socket.io')(server);

// const io=require("socket.io")(app)

var {con,getMysql} = require('./mysql/mysql.js');

var session = require('express-session')    //session
var multer  = require('multer')  //上传文件

var bodyParser=require("body-parser") //引入

var cors = require('cors')

app.use(cors())

//配置body-parser插件
app.use(bodyParser.urlencoded({extended:false}))    //这是解析表单的
app.use(bodyParser.json())    //这是解析json格式的 

app.use(session({
    secret: 'keyboard',  //添加的密码
    resave: true,  //强制保存session
    saveUninitialized: true,
    cookie: { secure: true,maxAge:1000*60*60*24 }
  }))

var upload = multer({ dest: 'uploads/' })

//引入登录路由模块
const login = require("./code/login")

//引入主页路由模块
const admin = require("./code/admin/index")

//引入个人中心路由模块
const user = require("./code/user/index")

//引入小说管理路由模块
const article = require("./code/article/index")

//引入小说章节管理路由模块
const chapter = require("./code/chapter/index")

//引入excel导入导出模块
const excel = require("./code/excel")

//引入聊天模块
const chat = require("./code/chat/chat")

//为聊天匹配路由
app.use("/chat",chat)
//为登录路由匹配路径
app.use("/excel", excel)  //当以/login开始的，接下来就去login.js中，去看匹配路径

//为登录路由匹配路径
app.use("/login", login)  //当以/login开始的，接下来就去login.js中，去看匹配路径

//为主页路由匹配路径
app.use("/", admin)  //当以/admin开始的，接下来就去admin中，去看匹配路径

//为主页路由匹配路径
app.use("/user", user)  //当以/user开始的，接下来就去admin中，去看匹配路径

//为主页路由匹配路径
app.use("/article", article)  //当以/article开始的，接下来就去admin中，去看匹配路径

//为章节管理路由匹配路径
app.use("/chapter", chapter)  //当以/article开始的，接下来就去admin中，去看匹配路径


//实时通讯
io.on("connection",async function(socket){  //socket是当前的连接对象
  // console.log(socket)
  //向所有人广播，有新用户
  // let str2=`select * from user where socketid=${socket.id}`
  // let data3=await getMysql(str2)
  // console.log(data3)
  io.sockets.emit("addUser",{
    id:socket.id,
    msg:"有新用户加入聊天",
  })

   //获取好友列表
   socket.on("users",async function(){
    let str=`select * from user`
    let data1=await getMysql(str)
    // console.log(data1)
    socket.emit("users",{
      data:data1
    })
   })

   //加入聊天，保存最新的socketid
   socket.on("login",async function(data){
     //先判断是否已经在线
     let str1="select * from user where isonline=? and id=?"
     let arr1=["true",data.id]
     let data1=await getMysql(str1,arr1)
     if(data1.length>0){
        socket.to(data1[0].socketid).emit("loginout",{
          msg:"账号在外地登录，被迫下线"
        })     
     }

    let str=`update user set socketid=?,isonline=? where id=?`
    let arr=[socket.id,'true',data.id]
    let data2=await getMysql(str,arr)
    socket.emit("login",{
      status:200,
      msg:"登陆成功"
    })
    

    //通知好友，我登录了
    socket.emit("adduser",{

    })

     //获取未阅读的消息
     let str2=`select * from user where socketid=?`
     let arr2=[socket.id]
     let data3=await getMysql(str2,arr2)
     let data4=JSON.parse(JSON.stringify(data3))[0]
    //  console.log(data4.id)
     
       let str5="select * from chat where isread=? and toauthorid=?"
       let arr5=["false",data4.id]
       let data5=await getMysql(str5,arr5)
      //  console.log(data5)
       socket.emit("unread",{
         data:JSON.parse(JSON.stringify(data5))
       })
       
     
   })

     

   //监听断开连接
   socket.on("disconnect",async function(){
    let str=`update user set socketid=?,isonline=? where socketid=?`
    let arr=[null,null,socket.id]
    let data2=await getMysql(str,arr) 
   })


  //向其他用户发送消息
  socket.on("toUser",async function(data){

    let str=`select * from user where id=${data.data.toauthorid}`
    let data1=await getMysql(str)

    //用户不在线
    if(JSON.parse(JSON.stringify(data1))[0].isonline!='true'){
      console.log("未登录")
       //将数据存到数据库
    let str1=`insert into chat (authorid,toauthorid,msg,time,isread) values (?,?,?,?,?)`
    let arr1=[data.data.authorid+"",data.data.toauthorid+"",data.data.msg+"",data.data.time+"",'false']
    let data2=await getMysql(str1,arr1)
    
      return
    }

    //用户在线
    //将数据存到数据库
    let str1="insert into chat (authorid,toauthorid,time,msg,isread) values (?,?,?,?,?)"
    let arr1=[data.data.authorid+"",data.data.toauthorid+"",data.data.time+"",data.data.msg,'false']
    let data2=await getMysql(str1,arr1)
    let socketid=JSON.parse(JSON.stringify(data1))[0].socketid
    socket.to(socketid).emit("sendMsg",{
      data:data
    })
  })
})



//开启端口监听socket
server.listen(3001);


//开启一般的服务器接口
app.listen(3000, () => {
    console.log("开启成功")
})
